package com.xm.xmwa1706090.web.controller;

import com.xm.xm.dto.ResultDto;
import com.xm.xm.dto.SearchDto;
import com.xm.xmwa1706090.web.base.BaseController;
import com.xm.xmwa1706090.service.dto.TradePayDto;
import com.xm.xmwa1706090.service.service.TradePayService;
import com.xm.xmwa1706090.service.util.wechat.XmlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 杭州新苗网络科技有限公司
 *
 * @author meihf
 * @create 2017/5/10
 * @description
 */
@RestController
@RequestMapping("/tradePay")
public class TradePayController extends BaseController {

    @Autowired
    TradePayService tradePayService;


    /**
     * 创建阿里支付参数
     */
    @RequestMapping(value = "/createAliPayParam", method = RequestMethod.POST)
    public ResultDto createPayParam(@RequestBody TradePayDto tradePayDto) {
        tradePayDto.setExterInvokeIp(getIpAddr());
        tradePayDto.setPayType(1);
        return tradePayService.createAli(tradePayDto);
    }


    /**
     * 支付宝回调方法
     */
    @RequestMapping(value = "/notifyAli",method = RequestMethod.POST)
    @ResponseBody
    public String notifyAli(HttpServletRequest request, HttpServletResponse response){
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            //乱码解决，这段代码在出现乱码时使用。
            try {
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            params.put(name, valueStr);
        }
        return tradePayService.notifyAli(params); //程序执行完后必须打印输出“success”（不包含引号）
    }



    /**
     * 创建微信支付参数
     */
    @RequestMapping(value = "/createWxParam", method = RequestMethod.POST)
    public ResultDto createWxParam(@RequestBody TradePayDto tradePayDto) {
        return tradePayService.unifiedorder(tradePayDto);
    }


    /**
     * 微信回调方法
     *
     */
    @RequestMapping(value = "/notifyWx", method = RequestMethod.POST)
    @ResponseBody
    public void notifyWx(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = XmlUtil.parseXml(request.getInputStream());
        } catch (IOException e) {
            logger.error(String.valueOf(e.getCause()));
        }

        // 告诉微信服务器，我收到信息了，不要在调用回调
        ResultDto resultDto = tradePayService.weChatNotify(map);
        if (resultDto.getCode() == 0){
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/xml;charset=utf-8");
            response.setHeader("Cache-control", "no-cache");
            PrintWriter out = response.getWriter();
            out.write((String) resultDto.getData());
        }
    }


    /**
     *  订单支付
     *
     * */
    @PostMapping(value = "/orderPay")
    @ResponseBody
    public ResultDto orderPay(@RequestBody SearchDto searchDto) {
        searchDto.getFiled().put("appUserId",getUserId());
        searchDto.getFiled().put("ip",getIpAddr());
        return tradePayService.orderPay(searchDto);
    }

    /**
     * 退款
     */
    @PostMapping(value = "/refund")
    @ResponseBody
    public ResultDto aliRefund(@RequestBody SearchDto searchDto){
        return tradePayService.refund(searchDto);
    }

}